﻿#pragma once
#ifndef __THREAD_LOCK_H__
#define __THREAD_LOCK_H__


#include <atomic>
#include <condition_variable>
#include "as_mutex.h"

namespace as
{
	namespace thread
	{
		//这个写法有问题,写锁还是会进入
		class RWLock
		{
		public:
			RWLock() = default;
			~RWLock() = default;

			void LockRead();
			void LockWrite();
			void ReleaseRead();
			void ReleaseWrite();

		private:
			std::atomic_ulong read_cnt_{ 0 };
			std::atomic_ulong write_cnt_{ 0 };
			std::atomic_bool write_flag_{ false };
			std::mutex mutex_;
			std::condition_variable cond_w_;
			std::condition_variable cond_r_;
		};

		class SpinLock
		{
		public:
			SpinLock() = default;
			SpinLock(const SpinLock &) = delete;
			SpinLock &operator= (const SpinLock &) = delete;
			void lock();
			void unlock() noexcept;

			bool try_lock() noexcept;

		private:
			SpinLock* mutex(){ return this; }
			std::atomic_flag flag = ATOMIC_FLAG_INIT;
		};

#define SPIN_GUARD_LOCK(V,S) std::lock_guard<SpinLock> V(S);

	}
}
#endif